package com.apobates.forum.toro.core;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Optional;

/**
 * js字符串表达式执行器
 */
public class JsExpressionExecutor implements StringExpressionExecutor {
    private final static ScriptEngine engine;
    static {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("javascript");
    }
    @Override
    public Optional<Object> execute(String expression) {
        try {
            Object tmp = engine.eval(expression);
            // System.out.println("[BE][JS]current value: "+tmp.toString()+", for expression: "+expression);
            return Optional.ofNullable(tmp);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Optional.empty();
    }
}
